<template>
  <div class="mr-4 flex w-48 flex-col border-r border-[rgba(255,255,255,.3)]">
    <div class="flex items-center justify-between p-4">
      <span>角色组</span>
      <Button size="small" @click="onAdd">+</Button>
    </div>
    <Tree
      :selectedKeys="selectedKeys"
      :tree-data="treeData"
      :field-names="fileNames"
      default-expand-all
      @select="onSelect"
      style="width: 280px"
    >
      <template #title="scope">
        <div class="flex w-32 justify-between">
          <span class="truncate">{{ scope.groupName }}</span>
          <Space>
            <EditOutlined @click="onEdit(scope.data)" />
            <DeleteOutlined @click="onDelete(scope.data)" />
          </Space>
        </div>
      </template>
    </Tree>

    <FormModal :columns="items" />
  </div>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import { useFormModal } from '@boeyo/hooks';
import { BoFormProps } from '@boeyo/ui';
import { Button, Modal, Space, Tree, TreeProps, message } from 'ant-design-vue';
import {
  createRoleGroup,
  deleteRoleGroup,
  fetchRoleGroup,
  updateRoleGroup,
} from '../api';

const emit = defineEmits<{
  search: [];
}>();

const roleList = defineModel('roleList');

const selectedKeys = computed<number[]>(() => {
  return [groupId.value as number];
});

const treeData = ref([]);
const fileNames: TreeProps['fieldNames'] = {
  title: 'groupName',
  key: 'id',
};

const groupId = defineModel('groupId');
const onSelect: TreeProps['onSelect'] = (_, item) => {
  groupId.value = item.node.id;
  emit('search');
};

const getList = async () => {
  const res: any = await fetchRoleGroup();
  treeData.value = res.rows;
  roleList.value = res.rows;

  if (!groupId.value && res.rows?.length) {
    groupId.value = res.rows[0].id;
    emit('search');
  }
};

const initData = () => {
  getList();
};

initData();

const items: BoFormProps['columns'] = [
  {
    valueType: 'input',
    dataIndex: 'groupName',
    title: '项目组名称',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入组名称',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入组名称',
    },
  },
];

const { FormModal, open } = useFormModal({
  size: 'small',
});

const onAdd = () => {
  open({
    title: '新增组名称',
    request: async (params: any) => {
      await createRoleGroup(params);
      getList();
    },
  });
};

const onEdit = (record: Record<string, any>) => {
  open({
    title: '修改组名称',
    defaultValue: record,
    request: async (params: any) => {
      await updateRoleGroup(params);
      getList();
    },
  });
};

const onDelete = async (record: Record<string, any>) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await deleteRoleGroup(record.id);
      getList();
      message.success('操作成功');
    },
  });
};
</script>
